package com.bowen.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bowen.common.utils.HttpUtils;
import com.bowen.gulimall.member.dao.MemberLevelDao;
import com.bowen.gulimall.member.entity.MemberLevelEntity;
import com.bowen.gulimall.member.exception.PhoneExistException;
import com.bowen.gulimall.member.exception.UsernameExistException;
import com.bowen.gulimall.member.vo.MemberLoginVo;
import com.bowen.gulimall.member.vo.MemberRegistVo;
import com.bowen.gulimall.member.vo.SociaIUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bowen.common.utils.PageUtils;
import com.bowen.common.utils.Query;

import com.bowen.gulimall.member.dao.MemberDao;
import com.bowen.gulimall.member.entity.MemberEntity;
import com.bowen.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(memberLevelEntity.getId());

        //检查用户名和手机号是否唯一,为了让controller能感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getPhone());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUsername());
        entity.setNickname(vo.getUsername());

        //密码要进行加密存储
        //由springboot提供的密码加解密工具  --》 可根据明文和密文进行对比验证
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(vo.getPassword());
        entity.setPassword(encode);

        this.baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer username1 = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (username1 > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1.查询
        MemberEntity entity = this.baseMapper.selectByUser(loginacct);

        if (entity == null) {
            //登录失败
            return null;
        } else {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, entity.getPassword());
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SociaIUser sociaIUser) throws Exception {
        //登录和注册合并逻辑
        String uid = sociaIUser.getUid();
        //1.判断当前社交用户是否已经登录过系统
        MemberDao dao = this.baseMapper;
        MemberEntity memberEntity = dao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //这个用户已经注册了
            //需要更换令牌和时间
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(sociaIUser.getAccess_token());
            update.setExpiresIn(sociaIUser.getExpires_in());
            dao.updateById(update);

            memberEntity.setAccessToken(sociaIUser.getAccess_token());
            memberEntity.setExpiresIn(sociaIUser.getExpires_in());
            return memberEntity;
        } else {
            //2.没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity regist = new MemberEntity();
            try {
                //3.查询当前社交用户的社交账号信息（昵称，头像等）
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token", sociaIUser.getAccess_token());
                map.put("uid", sociaIUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "GET", new HashMap<String, String>(), map);

                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");

                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {

            }
            regist.setSocialUid(sociaIUser.getUid());
            regist.setAccessToken(sociaIUser.getAccess_token());
            regist.setExpiresIn(sociaIUser.getExpires_in());
            dao.insert(regist);
            return regist;
        }
    }

}